package com.suse.warmstill.service.repository;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.suse.warmstill.common.enums.RedisEnum;
import com.suse.warmstill.common.utils.RedisCache;
import com.suse.warmstill.entity.TbUser;
import com.suse.warmstill.mapper.TbUserMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class UserRepository {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TbUserMapper userMapper;


    public void saveLoginImageCode(String redisKey, String code) {
        redisCache.setCacheObject(redisKey, code, 3, TimeUnit.MINUTES);
    }

    public Long getCapchaExpire(String redisKey) {
        return redisCache.getExpire(redisKey);

    }

    public String getCaptchaCode(String redisKey) {
        return redisCache.getCacheObject(redisKey);
    }

    public TbUser getUserByPhone(String phone) {
        final LambdaQueryWrapper<TbUser> tbUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tbUserLambdaQueryWrapper.eq(TbUser::getPhone, phone);
        return userMapper.selectOne(tbUserLambdaQueryWrapper);
    }

    public void singleUser(Long id) {
        String key = RedisEnum.LOGIN_OLD_USER + id;
        String tokenKey = RedisEnum.LOGIN_TOKEN + id;
        final String oldToken = redisCache.getCacheObject(key);
        //redis中存在 登入的 token 说明，需要踢下线,删除token， 登入需要通过存储在redis 的token进行校验

        if (StringUtils.isNotEmpty(oldToken)) {
            redisCache.deleteObject(tokenKey);
        }
        // redis中没有 旧的token。则存储旧的token。

        redisCache.setCacheObject(key, "oldToken");


    }

    public void update(TbUser user) {

        user.setGmtLoginTime(LocalDateTime.now());
        final LambdaQueryWrapper<TbUser> tbUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tbUserLambdaQueryWrapper.eq(TbUser::getId, user.getId());
        userMapper.update(user, tbUserLambdaQueryWrapper);
    }

    public void saveAccessToken(Long id, String accessToken) {
        String key = RedisEnum.LOGIN_TOKEN + accessToken;
        redisCache.setCacheObject(key, id, 12, TimeUnit.HOURS);
    }
}
